package com.hq.ims.data.interceptor.sql;


import com.hq.ims.data.interiorenum.EnumInsideFindDataScore;
import com.hq.ims.data.service.BaseCompanyService;
import com.hq.ims.data.utils.CurThreadLocalUtil;
import com.hq.utils.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import javax.annotation.Resource;

@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class XmlSqlDataRangeInterceptor implements Interceptor {

    @Resource
    private BaseCompanyService baseCompanyService;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            CurThreadLocalUtil.ThreadStore threadStore = CurThreadLocalUtil.getInstance().get();
            if (threadStore == null) {
                return invocation.proceed();
            }
            String curCompanyId = threadStore.getOrgId();
            if (StringUtils.isEmpty(curCompanyId)) {
                return invocation.proceed();
            }

            Object parameterObj = invocation.getArgs()[1];
            String inSqlValue = baseCompanyService.getDataRangeSql(
                    curCompanyId,
                    threadStore.getFindDataScore() == EnumInsideFindDataScore.CurrentAndBelow
            );
            if (parameterObj instanceof MapperMethod.ParamMap) {
                //兼容自定义复杂sql情况,在复杂sql中 在xml文件中自定义接in,在这里将参数写入map中 在xml中获取${findCompanyIdDataRange}
                MapperMethod.ParamMap parameter = (MapperMethod.ParamMap) parameterObj;
                parameter.put("findCompanyIdDataRange", inSqlValue);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return invocation.proceed();
    }
}


